package com.ruoyi.social.view;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.Apps.Utils.AppUtils;
import com.ruoyi.social.domain.*;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class RequestFullItem {
    private SocialProduct product;

    private SocialShop shop;

    private List<SocialVideo> videoList;

    private List<SocialKol> kolList;

    private List<SocialProductTrend> productTrendList;

    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
    private static final SimpleDateFormat DATE_TIME_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public RequestFullItem(JSONObject jsonObject) {

        // 解析产品信息
        if (jsonObject.containsKey("product")) {
            setProduct(parseProduct(jsonObject.getJSONObject("product")));
        }

        // 解析店铺信息
        if (jsonObject.containsKey("shop")) {
            setShop(parseShop(jsonObject.getJSONObject("shop")));
            product.setShopOutid(shop.getShopOutid());
        }


        // 解析视频信息
        if (jsonObject.containsKey("videos")) {
            JSONArray videosArray = jsonObject.getJSONArray("videos");
            List<SocialVideo> videos = new ArrayList<>();
            for (int i = 0; i < videosArray.size(); i++) {
                videos.add(parseVideo(videosArray.getJSONObject(i)));
            }
            setVideoList(videos);
        }

        // 解析KOL信息
        if (jsonObject.containsKey("authors")) {
            JSONArray authorsArray = jsonObject.getJSONArray("authors");
            List<SocialKol> authors = new ArrayList<>();
            for (int i = 0; i < authorsArray.size(); i++) {
                authors.add(parseKol(authorsArray.getJSONObject(i)));
            }
            setKolList(authors);
        }
    }

    public SocialProduct getProduct() {
        return product;
    }

    public void setProduct(SocialProduct product) {
        this.product = product;
    }

    public SocialShop getShop() {
        return shop;
    }

    public void setShop(SocialShop shop) {
        this.shop = shop;
    }

    public List<SocialVideo> getVideoList() {
        return videoList;
    }

    public void setVideoList(List<SocialVideo> videoList) {
        this.videoList = videoList;
    }

    public List<SocialKol> getKolList() {
        return kolList;
    }

    public void setKolList(List<SocialKol> kolList) {
        this.kolList = kolList;
    }

    public List<SocialProductTrend> getProductTrendList() {
        return productTrendList;
    }

    public void setProductTrendList(List<SocialProductTrend> productTrendList) {
        this.productTrendList = productTrendList;
    }

    /**
     * 解析产品信息
     */
    public static SocialProduct parseProduct(JSONObject productJson) {
        SocialProduct product = new SocialProduct();

        try {
            // 基础信息
            product.setProductOutid(productJson.getString("product_id"));
//            product.setProductPlatform("TikTok"); // 根据实际情况设置
            product.setProductCountry(productJson.getString("product_country"));
            product.setProductLink(productJson.getString("product_link"));
            product.setProductImg(productJson.getString("product_img"));

            // 类目信息
            JSONArray categoryL1 = productJson.getJSONArray("product_tt_category_l1");
            if (categoryL1 != null && !categoryL1.isEmpty()) {
                product.setProductTtCategory1(categoryL1.getString(0));
            }

            JSONArray categoryL2 = productJson.getJSONArray("product_tt_category_l2");
            if (categoryL2 != null && !categoryL2.isEmpty()) {
                product.setProductTtCategory2(categoryL2.getString(0));
            }

            JSONArray categoryL3 = productJson.getJSONArray("product_tt_category_l3");
            if (categoryL3 != null && !categoryL3.isEmpty()) {
                product.setProductTtCategory3(categoryL3.getString(0));
            }

            // 名称信息
            product.setProductNameOrigin(productJson.getString("product_name_en"));
//            product.setProductNameEn(productJson.getString("product_name_en"));
//            product.setProductNameCn(productJson.getString("product_name_en")); // 可根据需要翻译
//            product.setProductDetailOrigin(productJson.getString());

            // 价格和销量
            product.setProductSales(productJson.getLong("product_sold_count"));
            // 零售价
            String productPrice = productJson.getString("product_price"); // 售价
            String productOriginalPrice = productJson.getString("product_original_price"); //原价
            String productGmvCurrentPrice = productJson.getString("product_sale_amount"); // 销售GMV

            product.setProductPrice(AppUtils.extractNumberWithRegex(productPrice));
            product.setProductOriginalPrice(AppUtils.extractNumberWithRegex(productOriginalPrice)); //原价
            product.setProductCurrency(productJson.getString("product_price")); // 货币
            product.setProductGmvCurrentPrice(AppUtils.extractNumberWithRegex(productGmvCurrentPrice));
            product.setAjContent(productJson.toJSONString()); // 原文
            // 店铺信息
            product.setShopOutid(productJson.getString("shop_id"));


            // 品牌信息（从名称中提取或根据实际情况设置）
//            product.setProductBrand("SKINTIFIC");

            // 日期信息
//            if (productJson.containsKey("product_ctime")) {
//                product.setProductInfoUpdateData(DATE_TIME_FORMAT.parse(productJson.getString("product_ctime")));
//            }
            product.setProductInfoUpdateData(new Date());
            // 设置产品趋势数据（如果需要单独存储）
            if (productJson.containsKey("product_trend")) {
                JSONArray trendArray = productJson.getJSONArray("product_trend");
                List<SocialProductTrend> trends = new ArrayList<>();
                for (int i = 0; i < trendArray.size(); i++) {
                    trends.add(parseProductTrend(trendArray.getJSONObject(i), product.getProductOutid()));
                }
                product.setTrends(trends);
            }

        } catch (Exception e) {
            throw new RuntimeException("解析产品信息失败", e);
        }

        return product;
    }

    /**
     * 解析店铺信息
     */
    public static SocialShop parseShop(JSONObject shopJson) {
        SocialShop shop = new SocialShop();

        try {
            shop.setShopOutid(shopJson.getString("shop_id"));
//            shop.setShopPlatform("TikTok"); // 根据实际情况设置
            shop.setShopCountry(shopJson.getString("shop_country"));
            shop.setShopName(shopJson.getString("shop_name"));
            shop.setShopAvatar(shopJson.getString("shop_avatar"));
            shop.setShopSoldCount(AppUtils.extractNumberWithRegex(shopJson.getString("shop_sold_count")));
        } catch (Exception e) {
            throw new RuntimeException("解析店铺信息失败", e);
        }

        return shop;
    }

    /**
     * 解析KOL信息
     */
    public static SocialKol parseKol(JSONObject kolJson) {
        SocialKol kol = new SocialKol();

        try {
            kol.setKolOutid(kolJson.getString("kol_id"));
            kol.setKolUsername(kolJson.getString("kol_username"));
            kol.setKolNickname(kolJson.getString("kol_nickname"));
            kol.setKolProfileLink(kolJson.getString("kol_profile_link"));
            kol.setKolFollowers(kolJson.getLong("kol_followers"));
            kol.setKolCountry(kolJson.getString("kol_country"));
//            kol.setKolPlatform("TikTok"); // 根据实际情况设置
            kol.setKolLastUpdateData(new Date()); // 设置为当前日期

            // 如果有视频信息，可以设置到简介中
            if (kolJson.containsKey("videos")) {
                JSONArray videos = kolJson.getJSONArray("videos");
                if (videos != null && !videos.isEmpty()) {
                    StringBuilder bioBuilder = new StringBuilder();
                    for (int i = 0; i < Math.min(videos.size(), 3); i++) {
                        JSONObject video = videos.getJSONObject(i);
                        if (video.containsKey("video_desc")) {
                            bioBuilder.append(video.getString("video_desc")).append("; ");
                        }
                    }
                    if (bioBuilder.length() > 0) {
                        kol.setKolBioOrigin(bioBuilder.toString());
                    }
                }
            }

        } catch (Exception e) {
            throw new RuntimeException("解析KOL信息失败", e);
        }

        return kol;
    }

    /**
     * 解析视频信息
     */
    public static SocialVideo parseVideo(JSONObject videoJson) {
        SocialVideo video = new SocialVideo();

        try {
            video.setVideoOutid(videoJson.getString("post_id"));
            video.setVideoLink(videoJson.getString("post_link"));
//            video.setPostPlatform("TikTok"); // 根据实际情况设置
            video.setVideoCover(videoJson.getString("video_cover"));

            // 日期信息
            if (videoJson.containsKey("create_date")) {
                video.setVideoDate(DATE_FORMAT.parse(videoJson.getString("create_date")));
            }

            // 统计数据
            video.setVideoViews(videoJson.getLong("video_views"));
            video.setLikes(videoJson.getLong("likes"));
            video.setComments(videoJson.getLong("comments"));
            video.setShares(videoJson.getLong("shares"));

            // 销售额信息
            String saleAmountStr = videoJson.getString("sale_amount_show").trim();
            video.setGmvUsd(AppUtils.extractNumberWithRegex(saleAmountStr));

            // 脚本和描述
            video.setScriptSummaryOrigin(videoJson.getString("desc"));
            video.setScriptDetailOrigin(videoJson.getString("desc"));

            // 商品关联
            video.setProductOutid(videoJson.getString("product_id"));
            video.setKolOutId(videoJson.getString("author_id"));

        } catch (Exception e) {
            throw new RuntimeException("解析视频信息失败", e);
        }

        return video;
    }

    /**
     * 解析产品趋势信息
     */
    public static SocialProductTrend parseProductTrend(JSONObject trendJson, String productOutId) {
        SocialProductTrend trend = new SocialProductTrend();

        try {
            trend.setDate(DATE_FORMAT.parse(trendJson.getString("date")));
            trend.setRegion(trendJson.getString("region"));
            trend.setRegionName(trendJson.getString("region_name"));
            trend.setProductOutid(productOutId);
            trend.setSoldCount(trendJson.getLong("sold_count"));
            trend.setSaleAmount(trendJson.getLong("sale_amount"));

        } catch (Exception e) {
            throw new RuntimeException("解析产品趋势信息失败", e);
        }

        return trend;
    }

    public static void main(String[] args) {

    }
}
